<script setup lang="ts">
import {ref} from 'vue'
import {useAnalysetStore} from "@/store";
import AnalyesAPI from "@/api/system/analyes";
import CommonAPI from "@/api/common";
import router from "@/router";

const analyseStatusPage = useAnalysetStore()
const form = ref({})
const apportionForm = ref({
  sample_category_id: '', //样品类别id
  sample_category: '', //样品类别
  test_parms: '',//检测参数
  testparms_id: '',//检测依据id
  orderparam_id: '',//检测参数id
  test_method_number: '', //方法编号
  test_method: '', //方法编号
  check_uid: '', //校核人
  analysis_uid: '', //分析人
  notes: '', //备注
})
const userForm = ref({
  check_uid: '', //校核人
  analysis_uid: '', //分析人
  notes: '', //备注
  params: [], //参数
})

const paramsString = ref('')
const analyseTableList = ref([])
const sampleCategoryList = ref({})
const parametersList = ref([])
const methodList = ref([])
const personnelList = ref([])
const selectedUsers = ref([])
const assignedDialogVisible = ref(false)
const addTestParmsDialogVisible = ref(false)
const tableRefInstance = ref(null)

onMounted(() => {
  // 分析单列表
  getStatusPageDetail()
  //   获取检测类别
  getSampleCategoryList()
  //   获取分析人和校核人
  getPersonnelList()
})

// 获取分析单列表
function getStatusPageDetail() {
  let josn = {
    task_id: analyseStatusPage.analyseStatusForm.status,
    test_category: analyseStatusPage.analyseStatusForm.test_category,
  }
  AnalyesAPI.getAssignDetail(josn).then(data => {
    form.value = {...data.order, ...data.task_info}
    if (form.value.analysis_status === 1) {
      const formData = new FormData()
      formData.append('task_id', analyseStatusPage.analyseStatusForm.status);
      AnalyesAPI.echoCgTable(formData).then(res => {
        if (res !== null) {
          analyseTableList.value = JSON.parse(res.datas)
        } else {
          analyseTableList.value = data.test_parms.map(item => {
            return {
              ...item,
              test_parms_type: 0,
            };
          })
        }
      })
    } else {
      analyseTableList.value = data.test_parms.map(item => {
        return {
          ...item,
          test_parms_type: 0,
        };
      })
    }
    // analyseTableList.value = data.test_parms.map(item => {
    //     return {
    //         ...item,
    //         test_parms_type: 0,
    //     };
    // })
  })
}

// 获取分析人
function getPersonnelList() {
  AnalyesAPI.getPersonnel({group_id: 3}).then(data => {
    personnelList.value = data
  })
}

// 获取检测类别
function getSampleCategoryList() {
  CommonAPI.getSampleCategory().then(data => {
    sampleCategoryList.value = data
  })
}

// 勾选方法
function handleSelectionChange(selectedRows) {
  console.log(selectedRows)
  // 处理 paramsString 显示
  const grouped = selectedRows.reduce((acc, row) => {
    if (!acc[row.sample_category]) {
      acc[row.sample_category] = [];
    }
    acc[row.sample_category].push(row.test_parms);
    return acc;
  }, {});

  paramsString.value = Object.keys(grouped)
      .map(category => `${category}（${grouped[category].join('，')}）`)
      .join(' ');

  // **清空 userForm.params，并仅保留新选中的行
  userForm.value.params = selectedRows.map(row => {
    const globalIndex = analyseTableList.value.findIndex(item => item === row); // 在全局表格中查找索引
    return {
      ...row,
      index: globalIndex, // 使用全局索引
      analysis_names: row.analysis_names || '', // 保持现有分析人名字
      check_name: row.check_name || '', // 保持现有校核人名字
      analysis_uid: row.analysis_uid || [], // 分析人ID数组
      check_uid: row.check_uid || null, // 校核人ID
      notes: row.notes || '', // 保持现有备注
    };
  });
}


// 选中样品类型
function handleSelectionSampleChange(selectedRows: any) {
  apportionForm.value.sample_category = sampleCategoryList.value[selectedRows];
  getDetectionParametersList(apportionForm.value.sample_category_id)
}

// 获取对应的检测参数
function getDetectionParametersList(id: String | any) {
  CommonAPI.getDetectionParameters({category_id: id}).then(data => {
    parametersList.value = data
  })
}

// 选中检测参数
function handleSelectionParametersChange(selectedRows: any) {
  const selectedParam = parametersList.value.find(param => param.id === selectedRows);
  apportionForm.value.test_parms = selectedParam ? selectedParam.test_parms : null;
  getDetectionMethodList(apportionForm.value.testparms_id)
}

// 获取检测依据
function getDetectionMethodList(id: number | any) {
  CommonAPI.getDetectionMethod({test_parms_id: id}).then(data => {
    methodList.value = data
  })
}

function handleSelectionMethodChange(selectedRows: any) {
  const selectedParam = methodList.value.find(param => param.id === selectedRows);
  apportionForm.value.test_method = selectedParam ? selectedParam.test_method : null;
}


// 获取校核人
function handleFilterUser(selectedRows: any) {
  // 过滤出选中的用户
  selectedUsers.value = personnelList.value.filter(user => !selectedRows.includes(user.id));
}

// 关闭添加参数弹框
const handleAddTestParmsClose = () => {
  addTestParmsDialogVisible.value = false
  apportionForm.value = {}
}

// 关闭分派弹框
const handleClose = () => {
  assignedDialogVisible.value = false
  userForm.value = {}
  paramsString.value = ''
}

const handleOpenDialog = () => {
  if (paramsString.value !== '') {
    assignedDialogVisible.value = true
  } else {
    ElMessage({
      message: '请选择样品类别',
      type: 'warning',
    })
  }
}
const handleAddTestParmsDialog = () => {
  addTestParmsDialogVisible.value = true
}

// 确认分派
function handleAddApportion() {
  // 遍历 userForm.params 中的数据，根据索引更新 analyseTableList
  userForm.value.params.forEach(selected => {
    const index = selected.index; // 使用索引定位需要更新的行
    if (index !== -1) {
      // 更新分析人名字和 ID
      analyseTableList.value[index].analysis_names = personnelList.value
          .filter(person => userForm.value.analysis_uid.includes(person.id))
          .map(person => person.username)
          .join('，'); // 多人用逗号分隔

      // 更新校核人名字和 ID
      analyseTableList.value[index].check_name = personnelList.value
          .find(person => person.id === userForm.value.check_uid)?.username || ''; // 查找匹配的单个校核人

      analyseTableList.value[index].analysis_uid = userForm.value.analysis_uid; // 分析人ID
      analyseTableList.value[index].check_uid = userForm.value.check_uid; // 校核人ID
      analyseTableList.value[index].notes = userForm.value.notes; // 更新备注
    }
  });

  ElMessage.success('分派成功！');

  // 清空表格的选中状态
  if (tableRefInstance.value && tableRefInstance.value.clearSelection) {
    tableRefInstance.value.clearSelection(); // 调用表格的 clearSelection 方法
  }

  // 重置用户表单和参数字符串
  assignedDialogVisible.value = false;
  userForm.value = {};
  paramsString.value = '';
}

// 添加参数
function handleAddParameters() {
  // 创建一个新的行对象
  const newRow = {
    id: analyseTableList.value[analyseTableList.value.length - 1].id + 1,
    sample_category: sampleCategoryList.value[apportionForm.value.sample_category_id], // 使用对应的样品类别标签
    sample_category_id: Number(apportionForm.value.sample_category_id),
    testparms_id: apportionForm.value.testparms_id,
    test_method: apportionForm.value.test_method,
    test_parms: apportionForm.value.test_parms,
    test_method_number: apportionForm.value.test_method_number,
    test_parms_type: 1,
    analysis_names: personnelList.value
        .filter(person => apportionForm.value.analysis_uid.includes(person.id))
        .map(person => person.username)
        .join('，'),  // 分析人，多个用逗号分隔
    check_name: personnelList.value
        .find(person => person.id === apportionForm.value.check_uid)?.username || '',  // 校核人
    check_uid: apportionForm.value.check_uid,
    notes: apportionForm.value.notes,
    analysis_uid: apportionForm.value.analysis_uid,
  };
  // 将新的行添加到 analyseTableList 中
  analyseTableList.value.push(newRow);
  // 清空表单
  apportionForm.value = {
    sample_category_id: '',
    test_parms: '',
    testparms_id: '',
    test_method: '',
    analysis_uid: [],
    check_uid: null,
    notes: '',
  };
  // 关闭弹窗
  addTestParmsDialogVisible.value = false;
  // 提示成功
  ElMessage.success('参数添加成功！');
}

// 分派下发
function handleDispatchAllots() {
  const invalidRows = analyseTableList.value.filter(item => !item.analysis_names);
  if (invalidRows.length > 0) {
    return ElMessage({
      message: '存在未分配分析人员的数据，请检查！',
      type: 'warning',
    })
  }
  // 处理 data 数组，将 analysis_uid 转为字符串
  const processedData = analyseTableList.value.map(item => {
    // 手动构建对象，确保字段顺序与期望一致
    const newItem = {
      id: item.id,
      sample_category: item.sample_category, // 样品类别
      sample_category_id: Number(item.sample_category_id), // 样品类别ID，确保是数字
      testparms_id: item.testparms_id, // 测试参数ID
      test_method: item.test_method, // 测试方法
      test_parms: item.test_parms, // 测试参数
      test_method_number: item.test_method_number, // 测试方法编号
      test_parms_type: item.test_parms_type, // 测试参数类型
      analysis_names: item.analysis_names, // 测试参数类型
      analysis_uids: item.analysis_uid.join(','), // 将 analysis_uid 转为字符串
      check_name: item.check_name, // 校核人
      check_uid: item.check_uid, // 校核人ID
      notes: item.notes, // 备注
    };
    // 删除不需要的字段
    delete newItem.analysis_uid;
    delete newItem.orderparam_id;
    return newItem; // 返回新的对象
  });
  console.log(processedData)
  const formData = new FormData()
  formData.append('task_id', analyseStatusPage.analyseStatusForm.status);
  formData.append('datas', JSON.stringify(processedData));
//   分派下发接口
  AnalyesAPI.dispatchAllots(formData).then(data => {
    if (data !== null) {
      ElMessage.success('分派下发成功！')
      router.push({
        path: '/analyse/analyseIndex'
      })
    }
  })
}

// 保存草稿
const handleSave = () => {
  const formData = new FormData()
  formData.append('task_id', analyseStatusPage.analyseStatusForm.status);
  formData.append('datas', JSON.stringify(analyseTableList.value));
  AnalyesAPI.generateCgTable(formData).then(data => {
    if (data) {
      ElMessage.success('保存成功')
    }
  })
}

</script>

<template>
  <div class="card">
    <el-card class="box-card">
      <el-row>
        <el-col :span="6" class="syc-flex syc-flex-align-center ">
          任务名称：{{ form.task_name }}
        </el-col>
        <el-col :span="6" class="syc-flex syc-flex-align-center ">
          任务单号：{{ form.task_number }}
        </el-col>
        <el-col :span="6" class="syc-flex syc-flex-align-center ">
          关联委托单号：{{ form.order_number }}
        </el-col>
        <el-col :span="6" class="syc-flex syc-flex-align-center ">
          项目名称：{{ form.project_name }}
        </el-col>
        <el-col :span="6" class="syc-flex syc-flex-align-center ">
          检测周期：{{ form.test_period }}
        </el-col>
        <el-col :span="6" class="syc-flex syc-flex-align-center ">
          采样地点：{{ form.task_address }}
        </el-col>
        <el-col :span="6" class="syc-flex syc-flex-align-center ">
          分派人：{{ form.issueder == 0 ? '' : form.issueder }}
        </el-col>
        <el-col :span="6" class="syc-flex syc-flex-align-center ">
          分派时间：{{ form.issuedtime }}
        </el-col>
        <el-col :span="6" class="syc-flex syc-flex-align-center ">
          状态：{{
            form.analysis_status == '1' ? '待分派' : form.analysis_status == '2' ? '已分派' : form.analysis_status == '3' ? '草稿' : ''
          }}
        </el-col>
      </el-row>
    </el-card>
    <!--    表格内容-->
    <el-card class="box-card" style="margin-top: 30px">
      <div class="card-button">
        检测参数
        <div class="button">
          <el-button type="primary" @click="handleOpenDialog">分派</el-button>
          <el-button type="primary" @click="handleAddTestParmsDialog">添加参数</el-button>
        </div>
      </div>
      <el-table style="width: 100%" border ref="tableRefInstance" :data="analyseTableList"
                @selection-change="handleSelectionChange">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column prop="date" label="序号" align="center">
          <template #default="scope">{{ scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column prop="sample_category" label="样品类别" align="center">
        </el-table-column>
        <el-table-column prop="test_parms" label="检测参数" align="center">
          <template #default="scope">
            <div>
              <span v-show="scope.row.test_parms_type === 1">*</span>
              {{ scope.row.test_parms }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="test_method" label="检测依据" align="center">
          <template #default="scope">
            <span>{{ scope.row.test_method === null ? scope.row.test_method_number : scope.row.test_method }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="analysis_names" label="分析人" align="center">
        </el-table-column>
        <el-table-column prop="check_name" label="校核人" align="center">
        </el-table-column>
        <el-table-column prop="notes" label="备注" align="center">
        </el-table-column>
      </el-table>

    </el-card>
    <el-card class="box-card" style="margin-top: 30px">
      <div class="positioning-footer-button">
        <el-button @click="getStatusPageDetail">取 消</el-button>
        <el-button @click="handleSave">保存</el-button>
        <el-button type="primary" @click="handleDispatchAllots">分派下发</el-button>
      </div>
    </el-card>
    <!--      <div class="pagination">-->
    <!--        <el-pagination-->
    <!--            background-->
    <!--            layout="prev, pager, next"-->
    <!--            :total="20">-->
    <!--        </el-pagination>-->
    <!--      </div>-->
    <!--    分配任务-->
    <el-dialog title="分派" v-model="assignedDialogVisible" width="30%" center :before-close="handleClose">
      <el-form ref="form" :model="userForm" label-width="90px">
        <el-form-item label="检测参数：">
          {{ paramsString }}
        </el-form-item>
        <el-form-item label="分析人：">
          <el-select v-model="userForm.analysis_uid" multiple placeholder="请选择" @change="handleFilterUser">
            <el-option
                v-for="(label, value) in personnelList"
                :key="value"
                :label="label.username"
                :value="label.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="校核人：">
          <el-select v-model="userForm.check_uid" placeholder="请选择">
            <el-option
                v-for="(label, value) in selectedUsers"
                :key="value"
                :label="label.username"
                :value="label.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注：">
          <el-input v-model="userForm.notes" placeholder="单行输入"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer" style="display: flex;justify-content: center">
        <el-button @click="handleClose" style="width: 50%">取 消</el-button>
        <el-button type="primary" style="width: 50%" @click="handleAddApportion">确 定</el-button>
      </span>
    </el-dialog>
    <!--    添加检测参数-->
    <el-dialog title="添加参数" v-model="addTestParmsDialogVisible" width="30%" center
               :before-close="handleAddTestParmsClose">
      <el-form ref="form" :model="apportionForm" label-width="90px">
        <el-form-item label="样品类别：">
          <el-select v-model="apportionForm.sample_category_id" placeholder="请选择"
                     @change="handleSelectionSampleChange">
            <el-option
                v-for="(label, value) in sampleCategoryList"
                :key="value"
                :label="label"
                :value="value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="检测参数：">
          <el-input v-model="apportionForm.test_parms" placeholder="请输入"></el-input>
          <!--          <el-select v-model="apportionForm.testparms_id" placeholder="请选择"-->
          <!--                     @change="handleSelectionParametersChange">-->
          <!--            <el-option-->
          <!--                v-for="(label, value) in parametersList"-->
          <!--                :key="value"-->
          <!--                :label="label.test_parms"-->
          <!--                :value="label.id">-->
          <!--            </el-option>-->
          <!--          </el-select>-->
        </el-form-item>
        <el-form-item label="检测依据：">
          <el-input v-model="apportionForm.test_method" placeholder="请输入"></el-input>
          <!--          <el-select v-model="apportionForm.test_method_number" placeholder="请选择"-->
          <!--                     @change="handleSelectionMethodChange">-->
          <!--            <el-option-->
          <!--                v-for="(label, value) in methodList"-->
          <!--                :key="value"-->
          <!--                :label="label.test_method"-->
          <!--                :value="label.id">-->
          <!--            </el-option>-->
          <!--          </el-select>-->
        </el-form-item>
        <el-form-item label="分析人：">
          <el-select v-model="apportionForm.analysis_uid" multiple placeholder="请选择" @change="handleFilterUser">
            <el-option
                v-for="(label, value) in personnelList"
                :key="value"
                :label="label.username"
                :value="label.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="校核人：">
          <el-select v-model="apportionForm.check_uid" placeholder="请选择">
            <el-option
                v-for="(label, value) in selectedUsers"
                :key="value"
                :label="label.username"
                :value="label.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注：">
          <el-input v-model="apportionForm.notes" placeholder="单行输入"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer" style="display: flex;justify-content: center">
        <el-button @click="handleAddTestParmsClose" style="width: 50%">取 消</el-button>
        <el-button type="primary" style="width: 50%" @click="handleAddParameters">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.card {
  position: relative;
  padding: 20px 25px;
  //margin-bottom: 100px;
}

.pagination {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
}

.card-button {
  margin-bottom: 30px;
  display: flex;
  align-items: center;

  .button {
    margin-left: 20px;
  }
}

.syc-flex {
  display: flex;
}

.syc-flex-align-center {
  margin: 10px 0;
  align-items: center;
}

.syc-flex-justify-center {
  justify-content: center;
}

.positioning {
  width: 83%;
  position: fixed;
  bottom: 0;
  left: 0;
  margin-left: 210px;

  &-footer-button {
    width: 100%;
    //margin: 0 25px;
    //padding: 10px 20px;
    //background-color: white;
    display: flex;
    justify-content: flex-end;
  }

}

</style>
